package control;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import model.Player;
import model.Square;
import model.SquareType;
import ui.ContainerView;
import ui.TitleScreen;
import ui.Window;
import view.Map;
import view.PlayerRep;
import view.SquareRep;

/**
 * Represents the Game
 */
public class Game implements ActionListener {

	private final Timer loop;
	private int ticks;
	public static int TICK = 1000; // The time in milliseconds of a "tick".
	private final ContainerView container;
	private final Window w;
	public static int WIDTH = 40;
	public static int HEIGHT = 40;

	/**
	 * Game constructor
	 */
	public Game(){
		loop = new Timer(TICK, this);
		ticks = 0;
		w = Window.getInstance();
		container = new ContainerView();
		container.setLayout(new BorderLayout());
		container.add(new TitleScreen(new ActionListener(){
			public void actionPerformed(final ActionEvent arg0) {
				start();
			}
		}), BorderLayout.CENTER);
		w.add(container);
		w.setVisible(true);
	}

	/**
	 * getTicks returns the amount of ticks since start.
	 * @return amount of ticks as an integer.
	 */
	public synchronized int getTicks(){
		return ticks;
	}

	/**
	 * Stops the game loop.
	 */
	public synchronized void stop(){
		loop.stop();
	}

	/**
	 * Starts the game.
	 */
	public synchronized void start(){
		final Player player = new Player(60, 60);
		final PlayerRep playRep = new PlayerRep(player);
		final SquareType wall = new SquareType(Color.RED, "wall", true, false);
		final SquareType ground = new SquareType(Color.GRAY, "ground", false, true);
		final SquareRep[][] squareRep = new SquareRep[WIDTH][HEIGHT];
		final Square[][] squares = new Square[WIDTH][HEIGHT];
		for(int j = 0;j<squares[0].length;j++){
			for(int i = 0;i<squares.length;i++){
				if(i==10||j%5==0){
					squares[i][j] = new Square(wall);
				}else{
					squares[i][j] = new Square(ground);
				}
				squareRep[i][j] = new SquareRep(squares[i][j]);
			}
		}
		final Map region = new Map(squareRep);
		container.start(playRep, region);
		w.addKeyListener(new MovementListener(player, playRep, squares));
		loop.start();
	}

	/**
	 * Restarts loop.
	 */
	public synchronized void restart(){
		loop.start();
	}
	
	/**
	 * Stops and turns game invisible.
	 * Doesn't exit game.
	 */
	public void destroy() {
		stop();
		w.setVisible(false);
	}

	/**
	 * Performs a tick.
	 */
	public void actionPerformed(final ActionEvent arg0) {
		ticks++;
	}

	/**
	 * Initialize the game.
	 * @param e is a list of strings.
	 */
	public static void main(final String[] e){
		final Game game = new Game();

	}

}
